<template>
    <div class="counter_option">
        <div class="counter_content over">
            <div>
                <Form ref="optionForm" :model="optionForm" :rules="optionFormValidate" :label-width="100">
                    <Card>
                        <Divider>资产信息</Divider>
                        <div style="padding-right: 40px;">
                            <FormItem label="业务类型" prop="businessType">
                                <Select v-model="optionForm.businessType" placeholder="请选择业务类型" class="wprecent100"  @on-change="selectRadio">
                                    <Option :value="item.value" v-for="(item,index) in businessTypeList"
                                            :key="index">{{item.title}}
                                    </Option>
                                </Select>
                            </FormItem>
                            <FormItem label="品牌" prop="brandName" class="iconsearch_style" v-if="!isOldcar">
                                <div  @click="tagSearch">
                                    <Input v-model="optionForm.brandName" :disabled="isdisabled" placeholder="点击搜索后自动带入" icon="ios-search" class="wprecent100"/>
                                </div>
                           </FormItem>
                           <FormItem label="车型" prop="modelName" class="iconsearch_style" v-if="!isOldcar">
                                <div  @click="tagSearch">
                                    <Input v-model="optionForm.modelName"  :disabled="isdisabled" placeholder="点击搜索后自动带入" icon="ios-search" class="wprecent100"/>
                                </div>
                        </FormItem>
                            <FormItem label="款式" prop="styleName" class="iconsearch_style" v-if="!isOldcar">
                                <div  @click="tagSearch">
                                    <Input v-model="optionForm.styleName"  :disabled="isdisabled" placeholder="点击搜索后自动带入" icon="ios-search" class="wprecent100"/>
                                </div>
                           </FormItem>
                            <FormItem label="指导价" prop="guidePrice" v-if="!isOldcar">
                                <Input v-model="optionForm.guidePrice"  :disabled="isdisabled" placeholder="点击搜索后自动带入" class="wprecent100"/>
                            </FormItem>
                            <FormItem label="车辆价格(元)" prop="salePrice">
                                <Input v-model="optionForm.salePrice" placeholder="请输入车辆价格" class="wprecent100" @on-change="inputPrice"/>
                            </FormItem>
                            <FormItem label="附加金额" prop="addAmt">
                                <Input v-model="optionForm.addAmt" placeholder="请输入附加金额" class="wprecent100" @on-change="inputPrice"/>
                            </FormItem>
                        </div>
                    </Card>
                </Form>
                <Form ref="financialProdForm" :model="financialProdForm" :rules="financialProdFormValidate" :label-width="100">
                    <Card >
                        <Divider>金融产品</Divider>
                        <div  style="padding-right: 40px;">
                            <Row>
                                <FormItem label="还款方式" prop="payPattern">
                                    <Select v-model="financialProdForm.payPattern" placeholder="请选择还款方式" class="wprecent100">
                                        <Option :value="item.value" v-for="(item,index) in payPatternList"
                                                :key="index">{{item.title}}
                                        </Option>
                                    </Select>
                                </FormItem>
                                <FormItem label="实际利率(%)" prop="realRate">
                                    <Input v-model="financialProdForm.realRate"   placeholder="请输入实际利率" class="wprecent100"/>
                                </FormItem>
                                <FormItem label="贷款期限(月)" prop="loanLimit" >
                                    <InputNumber
                                    :min="0"
                                    class="wprecent100"
                                    v-model="financialProdForm.loanLimit"
                                    @keyup.native="changeNumber"
                                    ></InputNumber>
                                </FormItem>
                                <Row style="display: flex;">
                                    <Col span="12">
                                        <FormItem label="首付比例(%)" prop="downPayScale" >
                                            <Input v-model="financialProdForm.downPayScale"  placeholder="" @on-change="inputPayScale('downPayScale')" class="wprecent100"/>
                                        </FormItem>
                                    </Col>
                                    <Col span="12">
                                        <FormItem label="首付金额(元)" prop="downPayAmt" style="margin-left: 10px;">
                                            <Input v-model="financialProdForm.downPayAmt"  placeholder="" @on-change="inputPayAmt('downPayAmt')" class="wprecent100"/>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row  style="display: flex;" v-if="isTail">
                                    <Col span="12">
                                        <FormItem label="尾款比例(%)" prop="tailPayScale" >
                                            <Input v-model="financialProdForm.tailPayScale"  placeholder="" @on-change="inputPayScale('tailPayScale')" class="wprecent100"/>
                                        </FormItem>
                                    </Col>
                                    <Col span="12">
                                        <FormItem label="尾款金额(元)" prop="tailPayAmt" style="margin-left: 10px;">
                                            <Input v-model="financialProdForm.tailPayAmt"  placeholder="" class="wprecent100"/>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <FormItem label="贷款金额" prop="loanAmt">
                                    <Input v-model="financialProdForm.loanAmt" class="wprecent100" @on-change="inputLoanAmt(financialProdForm.loanAmt)"/>
                                </FormItem>
                            </Row>
                        </div>
                    </Card>
                </Form>
                <Row style="text-align: center;margin: 20px 0;">
                    <Button type="primary" size="default" @click="resetForm">重置</Button>
                    <Button type="primary" size="default"  @click="calculate">开始计算</Button>
                </Row>
            </div>
            <!--计算结果显示界面-->
            <div class="computedResult" v-if="isShowResult">
                <Card>
                    <Divider style="font-size: 18px;">计算结果</Divider>
                    <ul size="large">
                        <li>车辆价格:<span>{{optionForm.salePrice}}</span>元</li>
                        <li>贷款金额:<span>{{financialProdForm.loanAmt}}</span>元</li>
                        <li>首付金额:<span>{{financialProdForm.downPayAmt}}</span>元</li>
                        <li>还款总额:<span>{{resultObj.totalRent}}</span>元</li>
                        <li>利息总额:<span>{{resultObj.totalInterest}}</span>元</li>
                        <li>贷款期限:<span>{{financialProdForm.loanLimit}}</span>月</li>
                        <!-- <li>月供金额:<span>{{resultObj.totalRent}}</span>元</li> -->
                        <li>首期月供:<span>{{resultObj.monthPayAmt}}</span>元</li>
                        <li><Button @click="schedule()" type="primary">还款计划</Button></li>
                    </ul>
                </Card>
            </div>
        </div>
         <!--品牌车型弹窗-->
         <div v-if="isShowModel">
            <char-cascade @close-model="closeModel" @carinfo="carinfo"></char-cascade>
        </div>
        <Modal width="50%" v-model="proessModel" :footer-hide="true" @on-cancel="cancelModel">
            <div class="scheduleTitle">
                <span class="curScheStyle"> 车贷 </span>
            </div>
            <div class="counterSliderList">
                <Form ref="proessForm" :model="proessForm"
                        :label-width="140">
                    <Row v-for="(item,index) in proessForm.proessList" :key="index"
                            style="padding: 0px 30px;">
                        <Col :span="2">
                            <div style="padding-top: 8px;">
                                {{item.no}}<span>期</span>
                            </div>
                        </Col>
                        <Col :span="5">
                            <FormItem label="" :prop="'proessList['+index+'].inputValue'"
                                        class="inline-block mb10" :label-width="0">
                                <Input v-model="item.inputValue" placeholder=""
                                        @on-blur="getInputValue(item.inputValue,index,isreadonly)"
                                        :readonly="isreadonly" class="wprecent100"/>
                            </FormItem>
                        </Col>
                        <Col :span="16" offset="1">
                            <Slider :value="item.proessValue" range :disabled="true"
                                    :max="maxValue" :step="stepNumber"></Slider>
                        </Col>
                    </Row>
                </Form>
            </div>
            <div v-if="isShowCalculate" style="text-align: center;margin:0px;"
                 class="submit">
                <Button type="success" @click="calculateIntrate">计算</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
    import "../../../assets/css/base.css";
    import * as utils from '_p/afs-apply/assets/js/utils.js'
    import CharCascade from "@/components/char-cascade"
    import PlaceCascade from "@/components/place-cascade"
    import {getByTypes} from "_p/basic/api/admin/datadic.js";
    import {getProductSelectList} from "../../../api/apply-report/personal/financialProducts";
    import {
        getArbitraryRepaymentPlan
    } from "_p/afs-apply/api/apply-report/personal/financialProducts.js"
    export default {
        name: "counter",
        data() {
            let isSalePriceValiate = (rule, value, callback) => {
                if (value) {
                    if (!utils.isTwoDicmal(value)) {
                        callback(new Error("最多为两位小数"))
                        return;
                    } else {
                        // 销售价格小于等于指导价格
                        if (parseFloat(value) > parseFloat(this.optionForm.guidePrice)) {
                            callback(new Error("小于等于指导价"))
                            return;
                        }
                    }
                }
                callback()
            }
            return {
                isOldcar:false,
                isTail:false,
                isShowModel: false,
                isdisabled: true,
                isShowResult:false,
                //  业务类型
                businessTypeList: [],
                //还款方式
                payPatternList: [],
                //资产信息
                optionForm: {
                    businessType:"",//业务类型
                    brandName: "",
                    modelName: "",
                    styleName: "",
                    salePrice: "",//车辆价格
                    guidePrice: "",//指导价
                    addAmt:"0"
                },
                //金融产品
                financialProdForm: {
                    payPattern:"",
                    realRate:"",
                    loanLimit:0,
                    downPayScale:"",
                    downPayAmt:"",
                    tailPayScale:"",
                    tailPayAmt:"",
                    loanAmt:"",
                },
                resultObj:{
                    totalInterest:"",
                    totalRent:"",
                },

                isShowCalculate: false,
                proessForm: {
                    proessList: [],
                },
                proessModel:false,
                stepNumber: 0.01,
                maxValue: 800,
                isreadonly: true,

                financialProdFormValidate:{
                    payPattern:[
                        {required: true, message: "业务选择不能为空", trigger: "change"}
                    ],
                    realRate:[
                        {required: true, message: "实际利率不能为空", trigger: "blur"},
                        {validator:utils.isTwoDicmalValiate,trigger:"blur"}
                    ],
                    loanLimit:[
                        {required: true, message:"贷款期限不能为空", trigger: "blur",type:"number"},
                    ],
                    downPayScale:[
                        {required: true, message: "首付比例不能为空", trigger: "blur"},
                        {validator:utils.isTwoDicmalValiate,trigger:"blur"}
                    ],
                    downPayAmt:[
                        {required: true, message: "首付金额不能为空", trigger: "blur"},
                        {validator:utils.isTwoDicmalValiate,trigger:"blur"}
                    ],
                    tailPayScale:[
                        {required: true, message: "尾款比例不能为空", trigger: "blur"},
                        {validator:utils.isTwoDicmalValiate,trigger:"blur"}
                    ],
                    tailPayAmt:[
                        {required: true, message: "尾款不能为空", trigger: "blur"},
                        {validator:utils.isTwoDicmalValiate,trigger:"blur"}
                    ],
                    loanAmt:[
                        {required: true, message: "贷款金额不能为空", trigger: "blur"},
                        {validator:utils.isTwoDicmalValiate,trigger:"blur"}
                    ],
                    addAmt:[
                        {required: true, message: "附加金额不能为空", trigger: "blur"},
                        {validator:utils.isTwoDicmalValiate,trigger:"blur"}
                    ]
                },
                optionFormValidate: {
                    businessType:[
                        {required: true, message: "业务选择不能为空", trigger: "change"}
                    ],
                    brandName: [
                        {required: true, message: "品牌不能为空", trigger: "blur"}
                    ],
                    modelName: [
                        {required: true, message: "车型不能为空", trigger: "blur"}
                    ],
                    styleName: [
                        {required: true, message: "款式不能为空", trigger: "blur"}
                    ],
                    guidePrice: [
                        {required: true, message: "指导价不能为空", trigger: "blur"}
                    ],
                    salePrice: [
                        {required: true, message: "车辆价格不能为空", trigger: "blur"},
                        {validator: isSalePriceValiate, trigger: "blur"}
                    ],
                },
            }
        },
        components: {
            CharCascade,
            PlaceCascade
        },
        mounted() {
            this.initDatadic();
        },
        methods: {
            initDatadic(){
                //数据字典
                let arr = ["businessType","repaymentMethod"];
                 getByTypes(arr).then(res => {
                    if (res.code === "0000") {
                        this.businessTypeList=res.data.businessType;
                        this.payPatternList=res.data.repaymentMethod;
                    }
                });
            },
            selectRadio(val){
                console.log(val,"Val")
                if(val=="02"){
                    this.isOldcar=true;
                }else{
                    this.isOldcar=false;
                }
            },
            changeNumber() {
                document.getElementsByClassName('ivu-input-number')[0].getElementsByTagName('input')[0].addEventListener('keyup', (e) => {
                    let str = '' + e.target.value;
                    if (str.indexOf('.') != -1) {
                        let arr = str.split('');
                        console.log(arr,"arr")
                        arr.splice(arr.length - 1);
                        let str2 = arr.join('');
                        e.target.value = +str2;
                    }
                })
            },
            //重置表单
            resetForm() {
                this.$refs.optionForm.resetFields();
                this.$refs.financialProdForm.resetFields();
                this.resultObj.totalInterest="";
                this.resultObj.totalRent="";
                this.isShowResult=false;
            },
            validateAll(callback) {
                let self = this;
                Promise.all([Promise.resolve(self.$refs.optionForm.validate()), Promise.resolve(self.$refs.financialProdForm.validate())])
                    .then((validaes) => {
                        console.log(validaes, "validaes")
                        callback(validaes.filter(item => {
                            return !item
                        }).length == 0);
                    })
            },
            calculate(){
                this.validateAll((pass)=>{
                    if(pass){
                        let algorithmType="";
                        if(this.financialProdForm.payPattern=='0'){//等额本息 0
                            algorithmType="equalrental";
                        }else{ //等额本金 1
                            algorithmType="equalprincipal";
                        }
                        let param={
                            loanAmt:this.financialProdForm.loanAmt,
                            loanTerm:this.financialProdForm.loanLimit,
                            custRate:this.financialProdForm.realRate,
                            settleRate:this.financialProdForm.realRate,
                            algorithmType:algorithmType,
                        }
                        getArbitraryRepaymentPlan(param).then(res=>{
                            if(res.code=="0000"){
                                 this.isShowResult=true;
                                this.maxValue=res.data.maxRent;
                                 this.resultObj.totalInterest=res.data.totalInterest;
                                 this.resultObj.totalRent=res.data.totalRent;
                                 this.resultObj.monthPayAmt=res.data.costList[0].firstRent;
                                 this.proessForm.proessList=this.queryProessList(res.data.repaymentList)
                            }
                        })
                    }
                })

            },
             // 总的还款计划表
            queryProessList(repaymentList){
                let tempArr=[];
                repaymentList.forEach((item,index)=>{
                    let obj={
                        no:item.no,
                        inputValue:item.yueGong.toString(),
                        proessValue:[],
                    }
                    obj.proessValue[0]=0;
                    obj.proessValue[1]=item.yueGong;
                    tempArr.push(obj);
                })
                console.log(tempArr,"tempArr")
                return tempArr;
            },
            tagSearch(){
                this.isShowModel = true;
                this.$emit("open-model");
            },
            // 选中款式的查询后获取的车辆信息
            carinfo(obj) {
                this.optionForm.brandName = obj.curBrandName;
                this.optionForm.modelName = obj.curModelName;
                this.optionForm.styleName = obj.curStyleName;
                this.optionForm.guidePrice = obj.curGuidePrice;
                this.optionForm.salePrice = obj.curGuidePrice;

                this.brandId = obj.curBrandId;
                this.modelId = obj.curModelId;
                this.styleId = obj.curStyleId;
                this.valiateNewCar();
            },
            // 校验新车
            valiateNewCar() {
                let fieldArr = ['brandName', "modelName", "styleName", "guidePrice", "salePrice"];
                fieldArr.forEach((item, index) => {
                    this.$refs["optionForm"].validateField(item)
                })
            },
            closeModel(value) {
                this.isShowModel = value;
            },
             // 输入比例
            inputPayScale(type){
                if(utils.isTwoDicmal(this.financialProdForm[type])){
                    // let salePriceError="",addAmtError="";
                    // this.$refs.optionForm.validateField('carPrice',(salePriceError)=>{
                    //     salePriceError=salePriceError;
                    // })
                    // this.$refs.optionForm.validateField('addAmt',(addAmtError)=>{
                    //     addAmtError=addAmtError;
                    // })
                    if(this.optionForm.salePrice||this.optionForm.addAmt){
                        let price=utils.add(this.optionForm.salePrice,this.optionForm.addAmt);
                        let payScale=this.financialProdForm[type];
                        let tempScale=utils.divided(payScale,100)
                        let multiplyAmt=utils.multiply(price,tempScale);
                        console.log(multiplyAmt,"multiplyAmt-carLoan")
                        // 四舍五入
                        let payAmt=Math.round(multiplyAmt*100)/100;
                        if(type=="downPayScale"){
                            this.financialProdForm.downPayAmt=payAmt.toString();
                            this.computedLoanAmt(this.financialProdForm.downPayAmt);
                        }else if(type=="tailPayScale"){
                            this.financialProdForm.tailPayAmt=payAmt.toString();
                        }
                    }
                }
                if(type=='downPayScale'){
                    this.$refs.financialProdForm.validateField('downPayAmt');
                }else if(type=="tailPayScale"){
                    this.$refs.financialProdForm.validateField('tailPayAmt');
                }
            },
            // 输入金额
            inputPayAmt(type){
                if(utils.isTwoDicmal(this.financialProdForm[type])){
                    // let salePriceError="",addAmtError="";
                    // this.$refs.optionForm.validateField('carPrice',(salePriceError)=>{
                    //     salePriceError=salePriceError;
                    // })
                    // this.$refs.optionForm.validateField('addAmt',(addAmtError)=>{
                    //     addAmtError=addAmtError;
                    // })
                    if(this.optionForm.salePrice||this.optionForm.addAmt){
                        let price=utils.add(this.optionForm.salePrice,this.optionForm.addAmt);
                        let payAmt=this.financialProdForm[type];
                        // 计算贷款金额
                        this.computedLoanAmt(payAmt);
                        let tempScale=utils.divided(payAmt,price);
                        let multiplyScale=utils.multiply(tempScale,100);
                        console.log(multiplyScale,"multiplyScale-carLoan")
                        // 四舍五入
                        let payScale=Math.round(multiplyScale*100)/100;
                        if(type=="downPayAmt"){
                            this.financialProdForm.downPayScale=payScale.toString();
                        }else if(type=="tailPayAmt"){
                            this.financialProdForm.tailPayScale=payScale.toString();
                        }
                    }
                }
                if(type=='downPayAmt'){
                    this.$refs.financialProdForm.validateField('downPayScale');
                }else if(type=="tailPayAmt"){
                    this.$refs.financialProdForm.validateField('tailPayScale');
                }
            },
            computedLoanAmt(downPayAmt){
                console.log(downPayAmt,"downPayAmt")
                let remainAmt=0;
                remainAmt=utils.sub(this.optionForm.salePrice,downPayAmt);
                this.financialProdForm.loanAmt=remainAmt.toString()||'';
                this.$refs.financialProdForm.validateField('loanAmt');
            },
             // 输入贷款金额
            inputLoanAmt(loanAmt){
                this.financialProdForm.downPayAmt=utils.sub(this.optionForm.salePrice,loanAmt).toString();
                this.inputPayAmt('downPayAmt');
            },
            // 输入车辆价格或附加金额
            inputPrice(){
                if(utils.isTwoDicmal(this.optionForm.salePrice)&&utils.isTwoDicmal(this.optionForm.addAmt)){
                    if(this.financialProdForm.downPayScale){
                        this.inputPayScale('downPayScale')
                    }
                    if(this.financialProdForm.tailPayScale){
                        this.inputPayScale('tailPayScale')
                    }
                }
            },
            schedule(){
                this.proessModel=true;
            },
            cancelModel() {
                this.proessModel = false;
            },
        }
    }
</script>
<style>
    .counterSliderList  .ivu-slider-disabled .ivu-slider-button:hover{
        cursor: pointer;
    }
    .counterSliderList .ivu-slider-disabled .ivu-slider-button:hover,
    .counterSliderList .ivu-slider-disabled .ivu-slider-button-dragging{
        border-color:#2d8cf0
    }
    .counterSliderList .ivu-slider-disabled .ivu-slider-button{
       border-color:#2d8cf0;
    }
    .counterSliderList .ivu-slider-disabled .ivu-slider-bar{
        background-color: #57a3f3
    }
</style>
<style scoped>
    .counter_option{
        min-width: 1200px;
        max-width: 1600px;
        margin: auto;
    }
    .business_option {
        padding-top: 40px;
    }
    .business_content {
        background-color: #FCFCFC;
    }
    .counter_content{
        background-color: white;
        padding: 30px 30px 0;
        display: flex;
    }
    .counter_content>>>.ivu-divider{
        font-size: 18px;
    }
    .counter_content>div{
        width: 50%;
    }
    .counter_content>div:first-child{
        padding-right:100px;
    }
    .counter_content .computedResult{
        padding: 0 20px;
    }
    .counter_content .computedResult li{
        padding-bottom: 15px;
        color: #333333;
        border-bottom: 1px solid #dcdee2;
        margin-top: 15px;
    }
    .counter_content .computedResult li:last-child{
        border:none;
    }
    .counter_content .computedResult li>span{
        margin:0 3px;
        font-size: 16px;
    }
    .counterSliderList {
        padding-top: 30px;
        max-height: 500px;
        overflow-y: auto;
        overflow-x: hidden;
    }

    .scheduleTitle {
        padding-left: 30px;
        line-height: 20px;
        font-size: 14px;
    }

    .scheduleTitle span.curScheStyle {
        color: #0D8EF5;
    }
    /deep/ .ivu-input.ivu-input-small.ivu-input-disabled{
        background-color: #f3f3f305;
    }
</style>

